package com.stars.home.vmodel

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.util.Log
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.stars.home.BR
import com.stars.home.R
import com.stars.home.activity.MainActivity
import com.stars.home.config.ConfigRx
import com.stars.home.model.CityList
import com.stars.home.utils.net.NetEngine
import com.trailer.base.base.BApp
import com.trailer.base.base.BRepository
import com.trailer.base.base.BViewModel
import com.trailer.base.utils.UiSwitch
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import kotlinx.coroutines.launch
import okhttp3.Call
import org.json.JSONObject
import java.io.File
import java.util.regex.Pattern

class CertificationVModel(application: Application) : BViewModel<BRepository>(application) {

    var type=1

    var cityId:String=""
    var imgOne=MutableLiveData<String>()
    var imgTwo=MutableLiveData<String>()
    var imgThree=MutableLiveData<String>()
    var imgFour=MutableLiveData<String>()

    var cityList=MutableLiveData<List<CityList>>()

    var address:String?=null
    var longitude:String?=null
    var latitude:String?=null


    var lessType:String?=""//1的时候从首页进入


    @Bindable
    open var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }


    @Bindable
    open var card: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.card)
        }



    /**
     * url中是否含有中文
     *
     * @param str
     * @return
     */
    fun isContainChinese(str: String?): Boolean {
        val p = Pattern.compile("[\u4e00-\u9fa5]")
        val m = p.matcher(str)
        return m.find()
    }

    fun toUpImg(url:String){


        var name: String //文件名字不能含有中文
        val index =url.lastIndexOf("/")

        name = if (isContainChinese(url.substring(index + 1))) {
            System.currentTimeMillis().toString() + ".jpg"
        } else {
            url.substring(index + 1)
        }

        val requestCall = OkHttpUtils.post()
            .url(BApp.instance()!!.config()!!.baseUrl()+"app/upload")
            .addFile("file", name,  File(url))
            .build()

        requestCall.execute(object : StringCallback() {
            override fun onError(call: Call, e: Exception, id: Int) {
                bView.toast(bView.getStr(R.string.upload_pic_fail)+e)
                Log.e("-shy-", "onError: $e")

            }

            override fun onResponse(response: String, id: Int) {
                //地址
                Log.e("-shy-", "onResponse: ="+response )
                val root = JSONObject(response)
                var data=root.getString("data")
                var obj=JSONObject(data)
                var url= obj.getString("url")
//                var url=root1.get("url")
               // imagUrl.value = url
                if(type==1){
                    imgOne.value=url
                }
                if(type==2){
                    imgTwo.value=url
                }
                if(type==3){
                    imgThree.value=url
                }
                if(type==4){
                    imgFour.value=url
                }


            }
        })



    }


    fun toSubmit(){


        if (name.isNullOrEmpty()) {
            toast("请请输入身份证号")
            return
        }
        if (card.isNullOrEmpty()) {
            toast("请请输入身份证号")
            return
        }
        if(cityId.isNullOrEmpty()){
            toast("请选择城市")
            return
        }
        if(latitude==null){
            toast("请选择地址")
            return
        }
        if(imgOne.value.isNullOrEmpty()){
            toast("请上传本人身份证正面照片")
            return
        }
        if(imgTwo.value.isNullOrEmpty()){
            toast("请上传本人身份证反面照片")
            return
        }
        if(imgThree.value.isNullOrEmpty()){
            toast("请上传资质证书")
            return
        }
        if(imgFour.value.isNullOrEmpty()){
            toast("请上传职业照")
            return
        }

        viewModelScope.launch {
            var it=repository().lreq { NetEngine.service.auth(name,cityId,card,address,longitude,latitude,imgOne.value,imgTwo.value,imgThree.value,imgFour.value) }
           if(it.ok(true)){

//               if(lessType.equals("1")) {
//                   UiSwitch.single(repository().context, MainActivity::class.java)
//                   (repository().context as Activity).finish()
//               }else{
//                   val intent = Intent()
//                   var con = repository().context as Activity
//                   con.setResult(Activity.RESULT_OK, intent)
//                   con.finish()

                   RxBus.get().post(ConfigRx.CERTIFICATION_TO, lessType)

                   (repository().context as Activity).finish()
//               }
           }

        }


    }

    fun getCityList(){
        viewModelScope.launch{

            var it=repository().lreq { NetEngine.service.cityList() }

            if(it.ok()){
                cityList.value=it.data
            }
        }

    }


}
